<?php

namespace App\Http\Controllers;

use App\ServicesNew\CouponService;
use App\Utils\GenObjFromRequestUtil;
use App\VO\UserCoupon\MetaInfo\UserCouponFactory;
use App\VO\UserCoupon\MetaInfo\UserCouponSearchInfo;
use App\VO\UserCoupon\UserCouponIndexVO;
use App\VO\UserCoupon\UserCouponShowVO;
use Illuminate\Http\Request;

class UserCouponController extends BaseController
{
    /**
     * @api {get} /user/coupon  用户优惠券列表
     * @apiGroup Coupon
     *
     * @apiParam {Number} [used]  是否已经使用
     * @apiParam {Number} [expired]  是否已经过期
     *
     */
    /**
     * 优惠券列表
     * @param CouponService $couponService
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(CouponService $couponService, Request $request)
    {
        $userCouponSearchInfo = $this->getSearchInfoFromRequest($request);
        $userCouponSearchInfo->setUserId($this->getUserId());

        $couponCodeEntities = $couponService->getCouponEntities($userCouponSearchInfo);
        $count = $couponService->count($userCouponSearchInfo);

        $userCouponIndexVO = new UserCouponIndexVO();
        $userCouponIndexVO->setSearch($userCouponSearchInfo);
        $userCouponIndexVO->setTotal($count);
        foreach ($couponCodeEntities as $couponCodeEntity) {
            $userCouponIndexVO->addCoupon(UserCouponFactory::getCouponInfo($couponCodeEntity));
        }

        return $this->successJsonResult($userCouponIndexVO);
    }

    /**
     * @param Request $request
     * @return UserCouponSearchInfo
     */
    private function getSearchInfoFromRequest(Request $request)
    {
        /** * @var UserCouponSearchInfo $search */
        $search = GenObjFromRequestUtil::getObj(UserCouponSearchInfo::class, $request);

        return $search;
    }

    /**
     * @api {get} /user/coupon/{couponId}  优惠券详情
     * @apiGroup Coupon
     */
    /**
     * @param int $couponId
     * @param CouponService $couponService
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function show(int $couponId, CouponService $couponService)
    {
        $couponCodeEntity = $couponService->findCouponEntityByIdAndUserId($couponId, $this->getUserId());
        if (is_null($couponCodeEntity)) {
            return $this->showJsonResult(500, '优惠券不存在');
        }

        $userCouponShowVO = new UserCouponShowVO();
        $userCouponShowVO->setCoupon(UserCouponFactory::getCouponInfo($couponCodeEntity));

        return $this->successJsonResult($userCouponShowVO);
    }
}
